<script setup lang="ts">
import {
  reactive,
  getCurrentInstance,
  ComponentInternalInstance,
  defineEmits,
  ref,
  computed,
  defineProps,
  defineExpose,
  onMounted,
} from "vue";
import { themeStore, ITheme } from "@/store/modules/theme";
import moment from "moment";
import language from "@/lang/zh";
import { ElMessage, ElMessageBox } from "element-plus";
const themeColors: ITheme = themeStore().theme;
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const emits = defineEmits(["listenLink"]);

const state: any = reactive({
  showPopup: false,
  curMode: "dark",
  list: [],
  userInfo: null,
  isEdit: false,
});
// 搜索历史记录
const query = ref('');  // 用户输入的查询内容
// 计算属性：过滤后的匹配结果
const queryList = computed(() => {
  // 确保 data.value 是一个有效的数组
  if (!query.value) {
    return [];
  }
  // 使用 includes 实现模糊查询，忽略大小写
  return state.list.filter((item: { sessionName: string }) =>
    item.sessionName.toLowerCase().includes(query.value.toLowerCase())
  );
});

const getFileDetails = (item: any) => {
  return new Promise((resolve) => {
    if (item.resourceFile && item.fileId) {
      let urls = item.resourceFile.split(",");
      let ids = item.fileId.split(",");
      let docList: any = [];
      for (let i = 0; i < urls.length; i++) {
        const url = urls[i];
        fetch(url, {
          method: "HEAD", // 只获取文件头部信息
        })
          .then((response) => {
            // 获取文件大小（Content-Length header）
            const fileSize = response.headers.get("Content-Length");
            // 从 URL 中提取文件名
            const fileName = url.substring(url.lastIndexOf("/") + 1);
            docList.push({
              fileName: fileName.includes('_') ? fileName.substring(0, fileName.lastIndexOf('_')) : fileName,
              // file_size: formatFileSize(Number(fileSize)),
              url: url,
              file_id: ids[i],
              fileType: fileName.split('.').pop().toLowerCase(),//文档类型
            });
            if (docList.length === urls.length) {
              resolve(docList)
            }
          })
          .catch((error) => {
            console.error("无法获取文件信息", error);
          });
      }
    }
  });
};

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (size < 1024) {
    return `${size}B`;
  } else if (size < 1024 * 1024) {
    return `${(size / 1024).toFixed(2)}KB`;
  } else if (size < 1024 * 1024 * 1024) {
    return `${(size / (1024 * 1024)).toFixed(2)}MB`;
  } else {
    return `${(size / (1024 * 1024 * 1024)).toFixed(2)}GB`;
  }
};

const getTop3QaList = () => {
  proxy?.$api.get(process.env.VUE_APP_BASE_API_URL + "/wechatApi/getUserQAList").then((res: any) => {
    if (res.code === 200 && res.data?.length > 0) {
      let data = res.data;
      for (let i = 0; i < data.length; i++) {
        let newList: any = [];
        for (let j = 0; j < data[i].list.length; j++) {
          newList = newList.concat([
            {
              type: 0,
              text: data[i].list[j].questionContent,
              fileList: data[i].list[j].resourceFile ? data[i].list[j].resourceFile.split(',') : []
            },
            {
              ...data[i].list[j],
            },
          ]);
        }
        data[i].qaList = newList
      }
      state.list = data;
    }
  });
};
const props = defineProps({
  selectOldWin: {
    type: String,
    default: "",
  },
  state: {
    type: Boolean,
    default: "",
  },
  openNewWindow: {
    type: Function,
    required: true
  },
  isDisabled: {
    type: Boolean,
    default: false
  },
  modelType: {
    type: Boolean,
    default: false
  },

});
onMounted(() => {
  getTop3QaList();
  state.userInfo = JSON.parse(localStorage.getItem("userInfo") || '{}');
});

// 判断是否禁止操作
const isForbidden = () => {
  if (props.isDisabled) {
    ElMessage.warning("请先结束回答");
    return true;
  } else {
    return false;
  }
};

// 删除历史记录
const clearQaList = (id: string, selectedIndex: number) => {
  proxy?.$api.post(process.env.VUE_APP_BASE_API_URL + "/wechatApi/delUserSession", {
    sessionId: id
  }).then((res: any) => {
    if (res.code === 200) {
      state.list.splice(selectedIndex, 1);
      if (hisSelectedIndex.value !== null) {
        if (hisSelectedIndex.value == selectedIndex) {
          openNewWin();
          hisSelectedIndex.value = null;
        } else if (hisSelectedIndex.value > selectedIndex)
          hisSelectedIndex.value--;
      }
    } else {
      proxy.$showToast(res.msg);
    }
  });
};
// 查看历史对话
const setNewQa = async (e: string, list: any) => {
  let item = state.list.find((i: any) => i.sessionId === e);
  let newList: any = [];
  for (let j = 0; j < item.list.length; j++) {
    if (item.list[j].questionType === 6) {
      newList = newList.concat([
        {
          type: 0,
          text: item.list[j].questionContent,
          imgList: item.list[j].resourceFile
            ? item.list[j].resourceFile.split(",")
            : [],
        },
        {
          ...item.list[j],
        },
      ]);
    } else if (item.list[j].questionType === 7) {
      let fileList: any = [];
      if (item.list[j].resourceFile)
        fileList = await getFileDetails(item.list[j]);
      newList = newList.concat([
        {
          type: 0,
          text: item.list[j].questionContent,
          fileList,
        },
        {
          ...item.list[j],
        },
      ]);
    } else {
      newList = newList.concat([
        {
          type: 0,
          text: item.list[j].questionContent,
        },
        {
          ...item.list[j],
        },
      ]);
    }
  }
  item.qaList = newList;
  emits("listenLink", { id: e, list: newList });
  query.value = "";
  hisSelectedIndex.value = findIndexByName(e);
};

// 新建对话占位
const newSessionBox = () => {
  const newSession = reactive({
    sessionName: "新对话",
  })
  state.list.unshift(newSession);
  hisSelectedIndex.value = 0;
}

// 响应式变量，用于记录当前选中的边框栏
const hisSelectedIndex = ref()
// 更新历史记录选中状态
const updateSelectedValue = (newValue: number) => {
  hisSelectedIndex.value = newValue;
};
const findIndexByName = (id: string) => {
  return state.list.findIndex((item: { sessionId: string }) => item.sessionId.toLowerCase() === id.toLowerCase());
};

// 新建对话
const openNewWin = () => {
  if (props.openNewWindow && !props.isDisabled) {
    props.openNewWindow(props.modelType ? 8 : 1);  // 调用父组件的方法
    hisSelectedIndex.value = null;
  }
}

// 删除历史记录
const deleteButton = (id: string, selectedIndex: number) => {
  isForbidden();
  if (!props.isDisabled) {
    ElMessageBox.confirm(
      props.state ? language.messageEN.confirmDelete : language.messageZH.confirmDelete,
      props.state ? language.messageEN.reminder : language.messageZH.reminder,
      {
        confirmButtonText: props.state ? language.messageEN.confirm : language.messageZH.confirm,
        cancelButtonText: props.state ? language.messageEN.cancelAction : language.messageZH.cancelAction,
        type: 'warning',
      }
    )
      .then(() => {
        clearQaList(id, selectedIndex);
        ElMessage({
          type: 'success',
          message: props.state ? language.messageEN.deleteSuccess : language.messageZH.deleteSuccess,
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: props.state ? language.messageEN.cancelDelete : language.messageZH.cancelDelete,
        })
      })
  }
}
defineExpose({
  getTop3QaList,
  updateSelectedValue,
  newSessionBox
});
</script>

<template>
  <!-- 历史记录 -->
  <div class="container">
    <div class="top-con" id="top-con">
      <div class="header">
        <div class="header-container">
          <div class="new-chat" @click="isForbidden() ? '' : openNewWin()">
            <div class="con">
              <!-- <div v-if="!props.state"></div> -->
              <div class="text">
                <img src="@/assets/images/new.png" alt="新建对话" />
                <span>{{ props.state ? language.messageEN.newChat : language.messageZH.newChat }}</span>
              </div>
            </div>
          </div>
          <div class="history">
            <img src="@/assets/images/history.png" alt="历史记录" />
            <span>{{ props.state ? language.messageEN.history : language.messageZH.history }}</span>
          </div>
          <div class="search-history-container">
            <input type="text" class="search" v-model="query"
              :placeholder="props.state ? language.messageEN.searchHistory : language.messageZH.history" />
            <span class="search-icon">
              <img src="@/assets/images/search.png" alt="搜索" />
            </span>
            <div class="queryList" v-if="query">
              <ul v-if="queryList.length">
                <li v-for="(item, index) in queryList" :key="index">
                  <div id="his" @click="isForbidden() ? '' : setNewQa(item.sessionId, item.qaList)">
                    {{ item.sessionName }}
                  </div>
                </li>
              </ul>
              <p v-else>{{ props.state ? language.messageEN.noResults : language.messageZH.noResults }}</p>
            </div>
          </div>
          <div class="con">
            <div class="top">
              <div class="top-detail">
                <span>{{
                  props.state
                    ? language.messageEN.historyChats
                    : language.messageZH.historyChats
                }}</span>
              </div>
            </div>
            <div class="hislist">
              <div class="list" v-if="state.list.length > 0">
                <div class="item-box" v-for="(item, index) in state.list" :key="index">
                  <div class="list-item" :style="{
                    width: state.isEdit ? 'calc(100% - 32px)' : '100%',
                  }">
                    <span class="fs-14">
                      <div class="content-text" :class="{ 'hisselected': hisSelectedIndex === index }">
                        <div id="his" @click="isForbidden() ? '' : setNewQa(item.sessionId, item.qaList)">
                          {{ item.sessionName }}
                        </div>
                        <div class="del" v-if="state.isEdit" @click="deleteButton(item.sessionId, index)">
                          <span class="iconfont icon-shanchu1"></span>
                        </div>
                      </div>
                    </span>
                  </div>
                </div>
              </div>
            </div>
            <div class="historical-management" v-if="!state.isEdit" @click="state.isEdit = true">
              <img src="@/assets/images/manage.png" alt=" 管理对话" />
              <span>{{ props.state ? language.messageEN.manageChats : language.messageZH.manageChats }}</span>
            </div>
            <div class="historical-management" v-if="state.isEdit" @click="state.isEdit = false">
              <img src="@/assets/images/manage.png" alt=" 管理对话" />
              <span>{{ props.state ? language.messageEN.manageChats : language.messageZH.manageChats }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  border-radius: 14px;
  font-size: 14px;
  z-index: 101;
  background: #fff;
  box-shadow: 3px 0px 6px 0px rgba(92, 178, 255, 0.1);

  .top-con {
    position: relative;
    z-index: 2;
    // width: calc(100% - 60px);
    margin: 0 auto;

    .header-container {
      width: 12vw;
      margin: 0 auto;
      display: flex;
      flex-direction: column;

      .con {
        height: 77vh;
        display: flex;
        flex-direction: column;
      }

      .top {
        .top-detail {
          margin-top: 2vh;
          font-size: 12px;
          color: #999;
        }
      }

      .hislist {
        margin-top: 0.5vh;
        height: 65vh;
        overflow: auto;
        flex: 1;

        .list-item {
          width: 100%;
          height: 38px;
          font-size: 14px;
          color: #666;

          .content-text {
            width: 11.6vw;
            height: 100%;
            display: flex;
            margin: 12px 0;

            #his {
              height: 100%;
              min-width: 10vw;
              width: 100%;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              padding: 9px 14px;
            }

            div {
              display: inline-block;
            }
          }

          .hisselected {
            border-radius: 8px;
            color: #5CB2FF;
            background: rgba(92, 178, 255, 0.15);
          }

          .content-text:hover {
            cursor: pointer;
            border-radius: 8px;
            color: #5CB2FF;
            background: rgba(92, 178, 255, 0.15);
          }

          .del {
            margin-right: 14px;
            display: flex;
            align-items: center;
            color: #666;
            justify-content: center;
            
            span {
              display: block;
              width: 12px;
              height: 12px;
              line-height: 38px;
              font-size: 16px;
            }
          }

          .del:hover {
            color:#F56C6C;
          }
        }
      }

      .historical-management {
        height: 5vh;
        padding: 2vh 0.05vw 0;
        color: #666;
        font-size: 14px;
        border-top: #EAEAEA 1px solid;
        display: flex;
        align-content: center;

        img {
          width: 20px;
          height: 20px;
          margin: 0 10px;
        }
      }

      .historical-management:hover {
        cursor: pointer;
      }
    }

    .new-chat {
      width: 12vw;
      height: 4vh;
      border-radius: 38px;
      margin: 20px 0;
      // background: linear-gradient(68deg, #5cb2ff 24.37%, #ffb1b1 85.59%);
      background-color: #1196db;
      display: flex;
      align-items: center;
      justify-content: center;

      .con {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-around;
        color: #fff;

        img {
          width: 17px;
          height: 17px;
          margin-right: 6px;
        }

        .text {
          display: flex;
          align-items: center;
          width: fit-content;
        }
      }
    }

    .new-chat:hover {
      cursor: pointer;
    }

    .history {
      display: flex;
      align-items: center;
      color: #333;
      font-size: 16px;

      img {
        width: 16px;
        height: 16px;
        margin-right: 5px;
      }
    }

    .search-history-container {
      width: 12vw;
      height: 4vh;
      display: flex;
      align-items: center;
      background: rgba(153, 153, 153, 0.1);
      border: rgba(153, 153, 153, 0.2) 1px solid;
      line-height: 18px;
      border-radius: 38px;
      margin-top: 17px;
      padding: 5px;
      position: relative;

      .queryList {
        position: absolute;
        top: 39px;
        left: 0;
        background: rgba(245, 245, 245, 1);
        border-radius: 14px;
        width: 100%;
        max-height: 360px;
        overflow: auto;
        padding: 8px;
        border: rgba(153, 153, 153, 0.2) 1px solid;
        border-top: none;

        ul {
          list-style: none; //去掉标签默认的左边符号
          display: flex;
          flex-direction: column;
        }

        li {
          display: block;
          list-style-type: none; //去掉标签默认的左边符号
          text-align: center;
          height: 30px;
          display: flex;
          align-items: center;
          margin: 6px 0;

          div {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            text-align: left;
            padding: 2px 5px;
          }
        }

        li:hover {
          cursor: pointer;
          border-radius: 8px;
          color: #5CB2FF;
          background: rgba(92, 178, 255, 0.15);
        }
      }
    }

    input[type="text"] {
      background-color: transparent;
      border: none;
      outline: none;
      padding: 5px;
      width: 100%;
      font-size: 12px;
      line-height: 17px;
    }

    .search-icon {
      height: 16px;
      width: 16px;
      margin-right: 14px;

      img {       width: 100%;
        height: auto;
      }
    }
  }
}
</style>
